package com.ht.shop.controller;

import com.ht.shop.annotations.RequestMapping;
import com.ht.shop.pojo.CartItem;
import com.ht.shop.pojo.Order;
import com.ht.shop.pojo.TbAddress;
import com.ht.shop.pojo.TbUser;
import com.ht.shop.service.AddressService;
import com.ht.shop.service.CartService;
import com.ht.shop.service.OrderService;
import com.ht.shop.service.impl.AddressServiceImpl;
import com.ht.shop.service.impl.CartServiceImpl;
import com.ht.shop.service.impl.OrderServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RequestMapping("/order")
public class OrderController {
    private CartService cartService = new CartServiceImpl();
    private AddressService addressService = new AddressServiceImpl();
    private OrderService orderService = new OrderServiceImpl();


    @RequestMapping("/preView")
    public String preView(HttpServletRequest request, HttpServletResponse response) {
        TbUser loginUser = (TbUser) request.getSession().getAttribute("loginUser");
        Long uid = loginUser.getId();
        if (request.getSession().getAttribute("cart") == null) {
            List<CartItem> cartItemList = cartService.findCartByUid(uid);//获取到购物车数据
            request.getSession().setAttribute("cart", cartItemList);
        }

        if (request.getSession().getAttribute("addressList") == null) {
            //获取购物车数据
            //获取地址数据
            List<TbAddress> addressList = addressService.findAllAddressByUid(uid);
            //携带数据
            //跳转到预览页面
            request.getSession().setAttribute("addressList", addressList);
        }

        return "forward:/order.jsp";

    }

    @RequestMapping(("/create"))
    public String createOrder(HttpServletRequest request, HttpServletResponse response) {
        //创建订单需要知道购买的商品和数量,我们直接把购物车里面所有的数据都下单
        List<CartItem> cart = (List<CartItem>) request.getSession().getAttribute("cart");//先获取到要下单的商品
        //还得知道地址选择的是哪个, 地址从前端传过来
        String aid = request.getParameter("aid");//用户选择的地址
        Order order = orderService.createOrder(cart, aid);
        request.getSession().setAttribute("order",order);
        //携带数据 数据在哪?
        return "redirect:/orderSuccess.jsp";
    }
}
